package org.dyz.banana.platform.uaa.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.dyz.banana.platform.common.service.ITPermissionService;
import org.dyz.banana.platform.common.service.ITUserService;
import org.dyz.banana.platform.common.vo.TPermissionVo;
import org.dyz.banana.platform.common.vo.TUserVo;
import org.dyz.banana.platform.uaa.util.GrantedAuthorityImpl;
import org.dyz.banana.platform.uaa.util.JwtUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户登录认证信息查询
 * @author Louis
 * @date Jun 29, 2019
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ITUserService userService;
    @Autowired
    private ITPermissionService tPermissionService;
    
    
    public void setUserService(ITUserService userService) {
		this.userService = userService;
	}


	public void settPermissionService(ITPermissionService tPermissionService) {
		this.tPermissionService = tPermissionService;
	}


	@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUserVo user = userService.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("该用户不存在");
        }
        // 1. 如果权限存储在一个表：
        // 用户权限列表，根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比，决定是否可以调用接口
        List<TPermissionVo> grantedAuthorities = tPermissionService.getPermissionByUsername(username);
        List<GrantedAuthority> grantedList = new ArrayList<GrantedAuthority>();
        if(grantedAuthorities!=null && grantedAuthorities.size()!=0) {
        	for(TPermissionVo permissionVo:grantedAuthorities) {
        		grantedList.add(new GrantedAuthorityImpl(permissionVo.getAuthority()));
        	}
        }
        // 2. 如果权限存储在一个字段：（权限默认通过逗号分开）
//        grantedList = AuthorityUtils.commaSeparatedStringToAuthorityList("权限字段");

        return new JwtUserDetails(username, user.getPassword(), grantedList);
    }

}
